package com.quiz.bis.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.quiz.bis.domain.model.ExamGroupMember;
import com.quiz.bis.domain.model.ExamSubgroup;
import com.quiz.bis.domain.vo.StudentMemberVo;
import com.quiz.bis.mapper.ExamGroupMemberMapper;
import com.quiz.bis.mapper.ExamSubgroupMapper;
import com.quiz.bis.mapper.ExamSubgroupMemberMapper;
import com.quiz.bis.service.IStudentMemberService;
import com.quiz.common.core.domain.entity.SysUser;
import com.quiz.common.exception.ServiceException;
import com.quiz.common.mybatis.core.page.PageQuery;
import com.quiz.common.mybatis.core.page.TableDataInfo;
import com.quiz.common.utils.SecurityUtils;
import com.quiz.system.mapper.SysUserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 学生成员服务实现
 */
@Service
@RequiredArgsConstructor
public class StudentMemberServiceImpl implements IStudentMemberService {
    private final ExamGroupMemberMapper groupMemberMapper;
    private final ExamSubgroupMemberMapper subgroupMemberMapper;
    private final SysUserMapper userMapper;
    private final ExamSubgroupMapper subgroupMapper;

    @Override
    public TableDataInfo<StudentMemberVo> pageMemberList(Long groupId, PageQuery pageQuery) {
        // 1. 验证学生是否属于该考试组
        Long userId = SecurityUtils.getUserId();
        boolean isMember = groupMemberMapper.exists(
                Wrappers.lambdaQuery(ExamGroupMember.class)
                        .eq(ExamGroupMember::getExamGroupId, groupId)
                        .eq(ExamGroupMember::getUserId, userId)
                        .eq(ExamGroupMember::getApproveStatus, 1) // 已通过审核
                        .eq(ExamGroupMember::getDelFlag, 0)
        );

        if (!isMember) {
            throw new ServiceException("您不属于该考试组，无法查看成员");
        }

        // 2. 查询成员列表
        Page<ExamGroupMember> page = groupMemberMapper.selectPage(pageQuery.build(),
                Wrappers.lambdaQuery(ExamGroupMember.class)
                        .eq(ExamGroupMember::getExamGroupId, groupId)
                        .eq(ExamGroupMember::getApproveStatus, 1)
                        .eq(ExamGroupMember::getDelFlag, 0)
                        .orderByAsc(ExamGroupMember::getRole) // 负责人排在前面
                        .orderByDesc(ExamGroupMember::getCreateTime)
        );

        // 3. 转换为VO
        List<StudentMemberVo> voList = page.getRecords().stream().map(member -> {
            StudentMemberVo vo = new StudentMemberVo();

            // 设置用户信息
            SysUser user = userMapper.selectUserById(member.getUserId());
            if (user != null) {
                vo.setUserId(user.getUserId());
                vo.setUserName(user.getNickName() + "(" +user.getUserName() + ")");
                vo.setNickName(user.getNickName());
                if (member.getRole() == 1 || member.getRole() == 2){
                    if("0".equals(user.getSex())){
                        vo.setAvatar("https://images.icon-icons.com/2859/PNG/512/avatar_face_man_boy_profile_smiley_happy_people_icon_181659.png");
                    }else {
                        vo.setAvatar("https://images.icon-icons.com/2859/PNG/512/avatar_face_girl_female_woman_profile_smiley_happy_people_icon_181662.png");
                    }
                }
                else if (member.getRole() == 3) {
                    if("0".equals(user.getSex())){
                        vo.setAvatar("https://images.icon-icons.com/2121/PNG/512/boy_child_man_male_people_avatar_icon_131270.png");
                    }else {
                        vo.setAvatar("https://images.icon-icons.com/2121/PNG/512/girl_woman_braids_people_avatar_icon_131277.png");
                    }
                }





            }

            // 设置角色信息
            vo.setRole(member.getRole());
            vo.setRoleName(getRoleName(member.getRole()));

            // 设置分组信息
            if (member.getSubgroupIds() != null) {
                List<Long> subgroupIds = JSON.parseArray(member.getSubgroupIds(), Long.class);
                vo.setSubgroupIds(subgroupIds);
                vo.setSubgroupNames(getSubgroupNames(subgroupIds));
            }

            vo.setJoinTime(member.getCreateTime());

            return vo;
        }).collect(Collectors.toList());

        return TableDataInfo.build(voList, page.getTotal());
    }

    /**
     * 获取角色名称
     */
    private String getRoleName(Integer role) {
        switch (role) {
            case 1:
                return "主要负责人";
            case 2:
                return "次要负责人";
            case 3:
                return "考生";
            default:
                return "未知角色";
        }
    }

    /**
     * 获取分组名称列表
     */
    private List<String> getSubgroupNames(List<Long> subgroupIds) {
        if (subgroupIds == null || subgroupIds.isEmpty()) {
            return null;
        }

        return subgroupMapper.selectBatchIds(subgroupIds).stream()
                .map(ExamSubgroup::getName)
                .collect(Collectors.toList());
    }
}